const http = require('http')
const url = require('url')
const fs = require("fs")
const path = require('path')
const { writeData, createDataFile, createConfigFile, readDataFile } = require('./file')
const ipAddr = require('../lib/ipAddr')
const tryPort = require('../lib/tryPort')

/**
 * 创建服务
 * 
 * 发送post请求写入数据 { "language": 语言, "key": 索引, "value": 值 }
 * 
 * @param {number} port 服务端口
 * @param {string} outDir 文件输出目录
 */
function service(port, outDir) {
    // 获取可用端口，不可用自动加 1
    tryPort(port, (usePort) => {
        console.log('config', path.join(__dirname, './config.js'), path.resolve('./config.js'))

        // 生成、更新数据导入文件
        createDataFile(outDir)

        // 生成、更新配置文件
        createConfigFile(`export const config = { port: ${port}, outDir: '${outDir}', ip: '${ipAddr}'}`)

        // 启动服务
        http.createServer((req, res) => {
            res.setHeader("Access-Control-Allow-Origin", "*")
            res.setHeader("Access-Control-Allow-Headers", "*")
            res.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS")
            res.setHeader("Content-Type", "application/json")
            res.writeHead(200)

            let data = ''
            req.on('data', (chunk) => data += chunk)
            req.on('end', () => {
                switch (req.method) {
                    // POST请求（提交数据）
                    case 'POST':
                        if (data) {
                            // 发送post请求数据 { "language": 语言, "key": 索引, "value": 值 }
                            data = JSON.parse(data)
                            if (data.language && data.key) {
                                if (!data.value) data.value = ''
                                writeData(outDir, `${data.language}.json`, data.key, data.value)
                            }
                        }
                        res.write('Successfully submitted language-service !')
                        res.end()
                        break;

                    // GET请求（查询数据）
                    case 'GET':
                        const fileData = readDataFile(outDir)
                        res.write(JSON.stringify(fileData))
                        res.end()
                        break;

                    default:
                        res.write('Hello language-service !')
                        res.end()
                        break;
                }
            })
        }).listen(usePort)
    })
}

class LanguageService {
    /**
     * 多语言数据处理插件 
     * 
     * outDir 文件输出目录 默认在 src/language 目录
     * 
     * @param {object} options { outDir: string }
     */
    constructor(options) {
        this.port = 9900
        this.outDir = 'src/language'
        if (options && options.outDir) this.outDir = options.outDir

        service(this.port, this.outDir)
    }

    apply(compiler) {
        compiler.hooks.afterPlugins.tap('LanguageService', (stats) => {
            service(this.port, this.outDir)
        })
    }
}

module.exports = LanguageService
